package com.qfedu.controller;

import com.qfedu.common.JsonResult;
import com.qfedu.entity.User;
import com.qfedu.utils.StrUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

/**
 * @Author 刘浩
 * @Date 2020/8/25 10:13
 */
@Controller
@ResponseBody
public class UploadController {
    @RequestMapping("/upload.do")
    public JsonResult uploadFile(@RequestParam MultipartFile upfile, HttpSession session){
        User u = (User)session.getAttribute(StrUtils.LOGIN_USER);
        if (u==null){
            return new JsonResult(0,"未登录");
        }
        //1.上传文件的 目录
        String dir="E:/upload";
        //2.获取上传文件的名字
        String fileName = upfile.getOriginalFilename();
        //3.判断目录是否存在
        File dirFile = new File(dir);
        if (!dirFile.exists()){
            dirFile.exists();
        }
        //4.要保存文件的file对象
        File newFile = new File(dir, fileName);
        try {
            upfile.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new JsonResult(1,"上传成功");
    }
}
